package br.com.megasena.converter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import br.com.megasena.constantes.MegaSenaConstantes;
import br.com.megasena.file.decompress.MegaSenaDecompress;
import br.com.megasena.to.JogoTO;
import br.com.megasena.to.SenaResultTO;

public class MegaSenaConverter {

	private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

	private static Logger log = Logger.getLogger(MegaSenaConverter.class
			.getName());

	public static Set<SenaResultTO> createResults(final File resultFile)
			throws Exception {
		Set<SenaResultTO> results = new HashSet<SenaResultTO>();
		Document doc = Jsoup.parse(resultFile, MegaSenaConstantes.ENCODING);
		for (Element table : doc.select("table")) {
			for (Element row : table.select("tr")) {

				Elements tds = row.select("td");

				if (!tds.isEmpty()) {

					if (!StringUtil.isBlank(tds.get(0).ownText()) && StringUtil.isNumeric(tds.get(0).ownText())) {
						log.info("Convertendo o concurso: "
								+ tds.get(0).ownText());

						SenaResultTO senaResult = new SenaResultTO();

						senaResult
								.setConcurso(new Integer(tds.get(0).ownText()));

						senaResult.setDataSorteio(sdf.parse(tds.get(1)
								.ownText()));

						senaResult.setJogo(new JogoTO(new Integer(tds.get(2)
								.ownText()), new Integer(tds.get(3).ownText()),
								new Integer(tds.get(4).ownText()), new Integer(
										tds.get(5).ownText()), new Integer(tds
										.get(6).ownText()), new Integer(tds
										.get(7).ownText())));

						senaResult.setGanhadores(new Integer(tds.get(9)
								.ownText()));

						senaResult.setAcumulado(tds.get(15).ownText()
								.contains(MegaSenaConstantes.YES));

						results.add(senaResult);
					}
				}
			}
		}
		return results;
	}
}
